package com.xiongkw.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;

public class EncryptUtil {
    private static Cipher ecipher;
    private static Cipher dcipher;
    // 必须24个字符
    private static final String key = "*:@1$7!a*:@1$7!a*:@1$7!a";
    private static final String alg = "DESede";
    static {
        try {
            SecretKey skey = new SecretKeySpec(key.getBytes(), alg);
            ecipher = Cipher.getInstance(alg);
            dcipher = Cipher.getInstance(alg);
            ecipher.init(Cipher.ENCRYPT_MODE, skey);
            dcipher.init(Cipher.DECRYPT_MODE, skey);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 加密字符串
     *
     */
    public static String encrypt(String str) {
        if (str == null)
            return "";
        try {
            // Encode the string into bytes using utf-8
            byte[] utf8 = str.getBytes("UTF8");
            // Encrypt
            byte[] enc = ecipher.doFinal(utf8);
            // Encode bytes to base64 to get a string
            BASE64Encoder b = new BASE64Encoder();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            b.encode(enc, bos);
            enc = bos.toByteArray();
            return new String(enc);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    /**
     * 解密字符串
     *
     */
    public static String decrypt(String str) {
        if (str == null)
            return "";
        try {
            // Decode base64 to get bytes
            BASE64Decoder d = new BASE64Decoder();
            byte[] dec = d.decodeBuffer(str);
            // Decrypt
            byte[] utf8 = dcipher.doFinal(dec);
            // Decode using utf-8
            return new String(utf8, "UTF8");
        } catch (Exception e) {
            return str;
        }
    }

//    public static void main(String[] args) {
//       String ss = EncryptUtil.encrypt("sAwAhTf248");
//        System.out.println(ss);
//        String ee = EncryptUtil.decrypt(ss);
//        System.out.println(ee);
//    }
}
